<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type"
        content="text/html; charset=ISO-8859-1" />
  <title>Code Examples for Programming in Scala</title>
  <link rel="stylesheet" href="style.css" type="text/css"/>
</head>
<body>

<div id="mainTitles"><h3>Code Examples for</h3><h2>Programming in Scala</h2></div>  <p><a href="../index.html">
    Return to chapter index
  </a></p>
  <h2>9 Control Abstraction</h2>

  <p><a href="../../src/control-abstraction/transcript.txt">
    Sample run of chapter's interpreter examples
  </a></p>

  <ul>

    <li>9.1 <a href="#sec1">Reducing code duplication</a></li>
    <li>9.2 <a href="#sec2">Simplifying client code</a></li>
    <li>9.3 <a href="#sec3">Currying</a></li>
    <li>9.4 <a href="#sec4">Writing new control structures</a></li>
    <li>9.5 <a href="#sec5">By-name parameters</a></li>
    <li>9.6 <a href="#sec6">Conclusion</a></li>
  </ul>

  <h3><a name="sec1"></a>9.1 Reducing code duplication</h3>

  <pre><hr>
// In file <a href="../../src/control-abstraction/Files1.scala">control-abstraction/Files1.scala</a>

  object FileMatcher {
    private def filesHere = (new java.io.File(".")).listFiles

    def filesEnding(query: String) =
      for (file &lt;- filesHere; if file.getName.endsWith(query))
        yield file
  }

<hr>
// In file <a href="../../src/control-abstraction/Files1.scala">control-abstraction/Files1.scala</a>

  def filesContaining(query: String) =
    for (file &lt;- filesHere; if file.getName.contains(query))
      yield file

<hr>
// In file <a href="../../src/control-abstraction/Files1.scala">control-abstraction/Files1.scala</a>

  def filesRegex(query: String) =
    for (file &lt;- filesHere; if file.getName.matches(query))
      yield file

<hr>
  def filesMatching(query: String, <em>method</em>) =
    for (file &lt;- filesHere; if file.getName.<em>method</em>(query))
      yield file

<hr>
// In file <a href="../../src/control-abstraction/Files2.scala">control-abstraction/Files2.scala</a>

  def filesMatching(query: String,
      matcher: (String, String) =&gt; Boolean) = {

    for (file &lt;- filesHere; if matcher(file.getName, query))
      yield file
  }

<hr>
// In file <a href="../../src/control-abstraction/Files2.scala">control-abstraction/Files2.scala</a>

  def filesEnding(query: String) =
    filesMatching(query, _.endsWith(_))

  def filesContaining(query: String) =
    filesMatching(query, _.contains(_))

  def filesRegex(query: String) =
    filesMatching(query, _.matches(_))

<hr>
  (fileName: String, query: String) =&gt; fileName.endsWith(query)

<hr>
// In file <a href="../../src/control-abstraction/Files.scala">control-abstraction/Files.scala</a>

  object FileMatcher {
    private def filesHere = (new java.io.File(".")).listFiles

    private def filesMatching(matcher: String =&gt; Boolean) =
      for (file &lt;- filesHere; if matcher(file.getName))
        yield file
  
    def filesEnding(query: String) =
      filesMatching(_.endsWith(query))
  
    def filesContaining(query: String) =
      filesMatching(_.contains(query))
  
    def filesRegex(query: String) =
      filesMatching(_.matches(query))
  }

<hr>
  </pre>
  <h3><a name="sec2"></a>9.2 Simplifying client code</h3>

  <pre><hr>
  def containsNeg(nums: List[Int]): Boolean = {
    var exists = false
    for (num &lt;- nums)
      if (num &lt; 0)
        exists = true
    exists
  }

<hr>
  scala&gt; containsNeg(List(1, 2, 3, 4))
<span class="output">  res0: Boolean = false</span>

  scala&gt; containsNeg(List(1, 2, -3, 4))
<span class="output">  res1: Boolean = true</span>

<hr>
  def containsNeg(nums: List[Int]) = nums.exists(_ &lt; 0)

<hr>
  scala&gt; containsNeg(Nil)
<span class="output">  res2: Boolean = false</span>

  scala&gt; containsNeg(List(0, -1, -2))
<span class="output">  res3: Boolean = true</span>

<hr>
  def containsOdd(nums: List[Int]): Boolean = {
    var exists = false
    for (num &lt;- nums)
      if (num % 2 == 1)
        exists = true
    exists
  }

<hr>
  def containsOdd(nums: List[Int]) = nums.exists(_ % 2 == 1)

<hr>
  </pre>
  <h3><a name="sec3"></a>9.3 Currying</h3>

  <pre><hr>
  scala&gt; def plainOldSum(x: Int, y: Int) = x + y
<span class="output">  plainOldSum: (Int,Int)Int</span>

  scala&gt; plainOldSum(1, 2)
<span class="output">  res4: Int = 3</span>

<hr>
  scala&gt; def curriedSum(x: Int)(y: Int) = x + y
<span class="output">  curriedSum: (Int)(Int)Int</span>

  scala&gt; curriedSum(1)(2)
<span class="output">  res5: Int = 3</span>

<hr>
  scala&gt; def first(x: Int) = (y: Int) =&gt; x + y
<span class="output">  first: (Int)(Int) =&gt; Int</span>

<hr>
  scala&gt; val second = first(1)
<span class="output">  second: (Int) =&gt; Int = &lt;function&gt;</span>

<hr>
  scala&gt; second(2)
<span class="output">  res6: Int = 3</span>

<hr>
  scala&gt; val onePlus = curriedSum(1)_
<span class="output">  onePlus: (Int) =&gt; Int = &lt;function&gt;</span>

<hr>
  scala&gt; onePlus(2)
<span class="output">  res7: Int = 3</span>

<hr>
  scala&gt; val twoPlus = curriedSum(2)_
<span class="output">  twoPlus: (Int) =&gt; Int = &lt;function&gt;</span>

  scala&gt; twoPlus(2)
<span class="output">  res8: Int = 4</span>

<hr>
  </pre>
  <h3><a name="sec4"></a>9.4 Writing new control structures</h3>

  <pre><hr>
  scala&gt; def twice(op: Double =&gt; Double, x: Double) = op(op(x))
<span class="output">  twice: ((Double) =&gt; Double,Double)Double</span>

  scala&gt; twice(_ + 1, 5)
<span class="output">  res9: Double = 7.0</span>

<hr>
// In file <a href="../../src/control-abstraction/WithPrintWriter1.scala">control-abstraction/WithPrintWriter1.scala</a>

  def withPrintWriter(file: File, op: PrintWriter =&gt; Unit) {
    val writer = new PrintWriter(file)
    try {
      op(writer)
    } finally {
      writer.close()
    }
  }

<hr>
// In file <a href="../../src/control-abstraction/WithPrintWriter1.scala">control-abstraction/WithPrintWriter1.scala</a>

  withPrintWriter(
    new File("date.txt"),
    writer =&gt; writer.println(new java.util.Date)
  )

<hr>
  scala&gt; println("Hello, world!")
<span class="output">  Hello, world!</span>

<hr>
  scala&gt; println { "Hello, world!" }
<span class="output">  Hello, world!</span>

<hr>
  scala&gt; val g = "Hello, world!"
<span class="output">  g: java.lang.String = Hello, world!</span>

  scala&gt; g.substring { 7, 9 }
<span class="output">  &lt;console&gt;:1: error: ';' expected but ',' found.</span>
<span class="output">         g.substring { 7, 9 }</span>
<span class="output">                        ^</span>

<hr>
  scala&gt; g.substring(7, 9)
<span class="output">  res12: java.lang.String = wo</span>

<hr>
// In file <a href="../../src/control-abstraction/WithPrintWriter2.scala">control-abstraction/WithPrintWriter2.scala</a>

  def withPrintWriter(file: File)(op: PrintWriter =&gt; Unit) {
    val writer = new PrintWriter(file)
    try {
      op(writer)
    } finally {
      writer.close()
    }
  }

<hr>
// In file <a href="../../src/control-abstraction/WithPrintWriter2.scala">control-abstraction/WithPrintWriter2.scala</a>

  val file = new File("date.txt")

  withPrintWriter(file) {
    writer =&gt; writer.println(new java.util.Date)
  }

<hr>
  </pre>
  <h3><a name="sec5"></a>9.5 By-name parameters</h3>

  <pre><hr>
  withPrintWriter(file) {
    writer =&gt; writer.println(new java.util.Date)
  }

<hr>
// In file <a href="../../src/control-abstraction/Assert.scala">control-abstraction/Assert.scala</a>

  var assertionsEnabled = true

  def myAssert(predicate: () =&gt; Boolean) =
    if (assertionsEnabled &amp;&amp; !predicate())
      throw new AssertionError

<hr>
  myAssert(() =&gt; 5 &gt; 3)

<hr>
  myAssert(5 &gt; 3) // Won't work, because missing () =&gt; 

<hr>
// In file <a href="../../src/control-abstraction/Assert.scala">control-abstraction/Assert.scala</a>

  def byNameAssert(predicate: =&gt; Boolean) =
    if (assertionsEnabled &amp;&amp; !predicate)
      throw new AssertionError

<hr>
  byNameAssert(5 &gt; 3)

<hr>
  def boolAssert(predicate: Boolean) =
    if (assertionsEnabled &amp;&amp; !predicate)
      throw new AssertionError

<hr>
  boolAssert(5 &gt; 3)

<hr>
  scala&gt; var assertionsEnabled = false
<span class="output">  assertionsEnabled: Boolean = false</span>

  scala&gt; boolAssert(x / 0 == 0)
<span class="output">  java.lang.ArithmeticException: / by zero</span>
<span class="output">  	   at .&lt;init&gt;(&lt;console&gt;:8)</span>
<span class="output">          at .&lt;clinit&gt;(&lt;console&gt;)</span>
<span class="output">          at RequestResult$.&lt;init&gt;(&lt;console&gt;:3)</span>
<span class="output">          at RequestResult$.&lt;clinit&gt;(&lt;console&gt;)...</span>

<hr>
  scala&gt; byNameAssert(x / 0 == 0)

<hr>
  </pre>
  <h3><a name="sec6"></a>9.6 Conclusion</h3>


 <table>
 <tr valign="top">
 <td>
 <div id="moreinfo">
 <p>
 For more information about <em>Programming in Scala</em> (the "Stairway Book"), please visit:
 </p>
 
 <p>
 <a href="http://www.artima.com/shop/programming_in_scala">http://www.artima.com/shop/programming_in_scala</a>
 </p>
 
 <p>
 and:
 </p>
 
 <p>
 <a href="http://booksites.artima.com/programming_in_scala">http://booksites.artima.com/programming_in_scala</a>
 </p>
 </div>
 </td>
 <td>
 <div id="license">
 <p>
   Copyright &copy; 2007-2008 Artima, Inc. All rights reserved.
 </p>

 <p>
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
 </p>

 <p style="margin-left: 20px">
   <a href="http://www.apache.org/licenses/LICENSE-2.0">
     http://www.apache.org/licenses/LICENSE-2.0
   </a>
 </p>

 <p>
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
   implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 </p>
 </div>
 </td>
 </tr>
 </table>

</body>
</html>
